package com.senyint.sys.utils.net.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class SocketServerRunnable implements Runnable {

	private static final Logger log = LoggerFactory.getLogger(SocketServerRunnable.class);

	private Socket clientSocket;

	public void setClientSocket(Socket clientSocket) {
		this.clientSocket = clientSocket;
	}

	private String charset = "utf-8";

	public void setCharset(String charset) {
		this.charset = charset;
	}

	@Override
	public void run() {

		if (clientSocket != null) {
			String client = clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort();
			log.debug("Client {} received!", client);
			log.debug(Thread.currentThread().getName() + " handle " + client);
			InputStream inputStream = null;
			InputStreamReader inputStreamReader = null;
			BufferedReader bufReader = null;
			PrintWriter writer = null;
			try {
				clientSocket.setTcpNoDelay(true);
				clientSocket.setReuseAddress(true);
				inputStream = clientSocket.getInputStream();
				inputStreamReader = new InputStreamReader(inputStream, charset);
				bufReader = new BufferedReader(inputStreamReader);
				String msg = bufReader.readLine();
				log.debug("Client message {}", msg);
				String back = execWithMessage(msg);
				if (back != null) {
					writer = new PrintWriter(clientSocket.getOutputStream());
					log.debug("send backmessage {}", back);
					writer.println(back);
					writer.flush();
				}
			} catch (SocketException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					clientSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {

		}

	}

	public abstract String execWithMessage(String msg);

}
